//
//  ShowMemberViewController.m
//  SouthChina
//
//  Created by kc on 15/7/16.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "ShowMemberViewController.h"
#import "selectMemberTableViewCell.h"
#import "ContactDao.h"
#import "ContactDetailController.h"
#import "PersonalCenterView.h"
#import "TabbarViewController.h"
#import "AddressBookLeftViewController.h"
#import "TabbarView.h"

@interface ShowMemberViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    
    NSArray * keySortList;
    long childSize;
    NSMutableDictionary *keyCountMap;
    UISearchDisplayController *searchDisplayController;
    
}

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *tabtopstraint;

@end

@implementation ShowMemberViewController
@synthesize groupuserlist;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"ShowMemberViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];
    
    if([_CreateType isEqualToString:SHOW_USER])
    {
        [self addTitleBarWithBackBtn:_curOrgContact.mNAME needReturn:TRUE];
        _searchMember.showsCancelButton=NO;
        _searchMember.barStyle=UIBarStyleDefault;
        _searchMember.placeholder = @"搜索";
        _searchMember.delegate = self;
        
        
        _tabMember.delegate = self;
        _tabMember.dataSource = self;
        _tabMember.bounces=NO;
        
        [self resortContactList:@""];
        [_tabMember reloadData];
    }
    else
    {
        _searchMember.showsCancelButton=NO;
        _searchMember.barStyle=UIBarStyleDefault;
        _searchMember.placeholder = @"搜索";
        _searchMember.delegate = self;
        _searchMember.hidden = YES;
        _tabtopstraint.constant = 0;
        
        _tabMember.delegate = self;
        _tabMember.dataSource = self;
        _tabMember.bounces=NO;
        
        [_tabMember reloadData];
        [self addTitleBarWithBackBtn:@"管理员" needReturn:TRUE];
        
    }
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [self resortContactList:searchText];
    [_tabMember reloadData];
    
}
// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self resortContactList:@""];
    [_tabMember reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)resortContactList:(NSString*)key{
    NSArray * orgContactList = nil;
    //_curOrgContact.mID如果展示的最近联系人，
    if([_curOrgContact.mID isEqualToString: @"9999"])
    {
        orgContactList = [ContactDao queryRecentlyCcontact:key];
    }
    else
    {
        orgContactList = [ContactDao searcherNodeContact:_curOrgContact.mID key:key];
    }
    
    orgContactList= [orgContactList sortedArrayUsingComparator:^NSComparisonResult(Contact *p1, Contact *p2){
        
        return [p1.mQP compare:p2.mQP];
        
    }];
    
    childSize = orgContactList.count;
    keyCountMap = [[NSMutableDictionary alloc] init];
    
    bool isshow = [@"OFF" isEqualToString:[DE getGlobalVar:IS_SHOW_UNACTIVE_USER]];
    for (int i=0; i<orgContactList.count; i++) {
        
        Contact*contact =[orgContactList objectAtIndex:i];
        
        if (isshow)
        {
            if ([contact.mHEAD_IMG hasSuffix:@"defaultheadimg.png"]) {
                continue;
            }
        }
        NSString *key = [contact.mQP.length>=1?contact.mQP:@"#" substringToIndex:1];
        if ([keyCountMap objectForKey:key]) {
            NSMutableArray *array = [keyCountMap objectForKey:key];
            [array addObject:contact];
            [keyCountMap setObject:array forKey:key];
        }else{
            NSMutableArray *array = [[NSMutableArray alloc] init] ;
            [array addObject:contact];
            [keyCountMap setObject:array forKey:key];
        }
        
    }
    
    keySortList =[keyCountMap allKeys];
    keySortList = [keySortList sortedArrayUsingComparator:^NSComparisonResult(NSString *p1, NSString *p2){
        return [p1 compare:p2];
    }];
}


//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([_CreateType isEqualToString:SHOW_USER]) {
        return keySortList.count;
    }
    else
        return 1;
    
    
}
//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([_CreateType isEqualToString:SHOW_USER])
       return 20;
    else
        return 0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ([_CreateType isEqualToString:SHOW_USER])
       return 5;
    else
        return 0.001;
}


//右边显示的内容字母
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if ([_CreateType isEqualToString:SHOW_USER])
       return keySortList;
    else
        return [[NSArray alloc]init];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if ([_CreateType isEqualToString:SHOW_USER])
      return [keySortList objectAtIndex:section] ;
    else
        return @"";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_CreateType isEqualToString:SHOW_USER])
    {
        NSString *key = [keySortList objectAtIndex:section];
        NSArray *aray = [keyCountMap objectForKey:key];
        return aray.count;
    }
    else
        return  groupuserlist.count;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * CellIdentifier = @"selectMemberTableViewCell";
    selectMemberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    if ([_CreateType isEqualToString:SHOW_USER])
    {
        NSString *key = [keySortList objectAtIndex:indexPath.section];
        NSArray *aray = [keyCountMap objectForKey:key];
        Contact *contact =[aray objectAtIndex:indexPath.row];
        
        [cell setSelectMemberTableViewCell:contact];
       
    }
    else
    {
        NSArray *arrlist = [groupuserlist allObjects];
        Contact *contact = arrlist[indexPath.row];
        NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
        
        [cell.headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        cell.headImage.layer.cornerRadius = cell.headImage.frame.size.width / 2;
        cell.headImage.clipsToBounds = YES;
        
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",contact.mNAME];
        cell.detailLabel.hidden = YES;
    }
    [cell.checkBox setHidden:YES];
    cell.imagexconstraint.constant = -25;
    return cell;
}

- (BOOL)containsContact:(NSMutableSet*) set contact:(Contact *)contact
{
    for (Contact * i   in  set)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            return YES;
        }
    }
    return NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选择某个人");
    if([_CreateType isEqualToString:SHOW_USER])
    {
        NSString *key = [keySortList objectAtIndex:indexPath.section];
        NSArray *aray = [keyCountMap objectForKey:key];
        Contact *contact =[aray objectAtIndex:indexPath.row];
        if([contact.mID isEqualToString:DE.userId]) //自己的话，弹出个人中心主界面
        {
            NSLog(@"点击的是自己");
             [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
            TabbarViewController * tab = (TabbarViewController *) kAppDelegate.iCSDrawerController.centerViewController;
            [tab.tabbar.tabbar selectItemAtIndex:4];
        }
        else
        {
            NSLog(@"点击的是别人.....contact.mID....%@",contact.mID);
            MessageViewController * message = [[MessageViewController alloc]init];
            NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"2",@"record_DB_ID":contact.mPK_ID,
                                   @"recordID":contact.mID};
            
            message.sessInfo = dicc;
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
        }
    }
    else
    {
        ContactDetailController *person = [[ContactDetailController alloc]init];
        NSArray *arrlist = [groupuserlist allObjects];
        Contact *contact = arrlist[indexPath.row];
        person.contactId = contact.mID;
        person.TypeContact = @"2";
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:person animated:NO];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"点击艺术字体");
    if (buttonIndex==0) {
        [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
